package com.prb.factory;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import java.io.InputStream;
import java.lang.reflect.Field;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class XmlBeanFactory {

    public static Map<String , Object> beanMap = new ConcurrentHashMap<>();

    static {

        InputStream is = XmlBeanFactory.class.getClassLoader().getResourceAsStream("src/main/test/beans.xml");

        SAXReader saxReader = new SAXReader();

        try {
            Document read = saxReader.read(is);

            Element root = read.getRootElement();

            List<Element> beans = root.selectNodes("//bean");

            for (Element bean : beans) {
                String beanId = bean.attributeValue("id");
                String classPath = bean.attributeValue("class");

                Class<?> clazz = Class.forName(classPath);
                Object o =  clazz.newInstance();
                beanMap.put(beanId , o);

            }

            List<Element> propertiesList = root.selectNodes("//properties");
            for (Element element : propertiesList) {
                Element parent = element.getParent();
                String beanId = parent.attributeValue("id");
                Object bean = beanMap.get(beanId);
                Field field = bean.getClass().getDeclaredField(element.attributeValue("name"));
                field.setAccessible(true);
                field.set(bean , beanMap.get(element.attributeValue("ref")));

            }


        } catch (DocumentException e) {
            e.printStackTrace();
        }catch (ClassNotFoundException e) {
            e.printStackTrace();
        }catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        }catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

    }

    public static Object getBean(String name){

        Object bean = beanMap.get(name);

        return bean;

    }

}
